<template>
  <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
    v-model="isShowInstrumentDialog" title="新增 / 编辑使用说明书" width="40%" destroy-on-close @close="reset">
    <el-form label-width="85px" ref="formRef" :model="form" :rules="rules" :disabled="!form.isShowFile">
      <el-form-item label="文件名称：" prop="fileMc">
        <el-input maxlength="100" placeholder v-model="form.fileMc" clearable />
      </el-form-item>

      <el-form-item label="文件编号：" prop="fileCode">
        <el-input maxlength="100" placeholder v-model="form.fileCode" clearable />
      </el-form-item>
      <fileUpload v-model="form.fileList" />
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="success" @click="saveBtnClick">确 定</el-button>
        <el-button type="danger" @click="cancelBtnClick">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { addFileItemAPI } from "@/api/resource/instrumentItem";

const props = defineProps({
  instrumentId: {
    type: String,
  },
});
const emits = defineEmits(["childrenSaveBtn"]);
const { proxy } = getCurrentInstance();
const isShowInstrumentDialog = ref(false);

const form = ref({
  fileList: [],
});

const rules = ref({
  fileMc: [{ required: true, message: "文件名称不能为空", trigger: "blur" }],
  fileCode: [{ required: true, message: "文件编号不能为空", trigger: "blur" }],
});

const reset = () => {
  proxy.resetForm("formRef");
  form.value = {};
};

const saveBtnClick = () => {
  if (form.value.fileList.length) {
    proxy.$refs["formRef"].validate(async (valid) => {
      if (valid) {
        if (!form.value.groupId) form.value.groupId = props.instrumentId;
        form.value.fileType = 16;
        await addFileItemAPI(form.value);

        if (form.value.dataId) {
          proxy.$modal.msgSuccess("编辑成功");
        } else {
          proxy.$modal.msgSuccess("新增成功");
        }
        emits("childrenSaveBtn");
        isShowInstrumentDialog.value = false;
      }
    });
  } else {
    proxy.$modal.msgError("请选择您要上传的文件");
  }
};

const cancelBtnClick = () => {
  isShowInstrumentDialog.value = false;
};

watch(() => form.value.fileList, () => {
  if(!form.value.fileList) return;
  if (form.value.fileList.length > 0) {
    form.value.fileMc = form.value.fileList[0].fileName
  } else {
    form.value.fileMc = ""
  }
})

defineExpose({
  isShowInstrumentDialog,
  form,
});
</script>
